package com.weblearning.tliasweb.filter;

import com.alibaba.fastjson.JSONObject;
import com.weblearning.tliasweb.pojo.Result;
import com.weblearning.tliasweb.utils.JwtUtils;
import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

import java.io.IOException;

@Slf4j
//@WebFilter(urlPatterns = "/*")
public class LoginCheckFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest req=(HttpServletRequest) servletRequest;
        HttpServletResponse resp=(HttpServletResponse) servletResponse;


        //包含了url 则是登录操作 直接放行
         String url = req.getRequestURL().toString();
        log.info("请求url" +url);

        if(url.contains("login")){
            log.info("登录放行 ");
            filterChain.doFilter(servletRequest,servletResponse);
            return;
        }

        String jwt=req.getHeader("token");

        //判断token 是空？
        if(!StringUtils.hasLength(jwt)){
            log.info("请求头token为空 登录失败");
            Result error= Result.error("NOT_LOGIN");
            String noLogin = JSONObject.toJSONString(error);
            resp.getWriter().write(noLogin);
            return;
        }

        //判断token true?
        try {
            JwtUtils.parseJWT(jwt);
        } catch (Exception e) {
            e.printStackTrace();
            log.info("token错误");
            Result error = Result.error("token错误");
            String noLogin = JSONObject.toJSONString(error);
            resp.getWriter().write(noLogin);
            return;
        }

        //放行
        log.info("token正确 放行");
        filterChain.doFilter(req,resp);

    }
}
